package com.easylinkin.linkappapi.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.investigation.entity.InvestigationTaskDetail;
import com.easylinkin.linkappapi.investigation.service.InvestigationTaskDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;

/**
 * <p> 隐患排查监控页面的监听</p>
 */
@ServerEndpoint("/investigationBigScreenListener/{tenantId}/{userId}")
@Component
public class InvestigationBigScreenListener  extends Listener {
    private static final Logger LOGGER = LoggerFactory.getLogger(InvestigationBigScreenListener.class);

    private static CopyOnWriteArraySet<Listener> webSocketSet = new CopyOnWriteArraySet<>();
    //这里使用静态，让service属于类
    private static InvestigationTaskDetailService investigationTaskDetailService;

    @Override
    @OnOpen
    public void onOpen(Session session, @PathParam("tenantId") String tenantId, @PathParam("userId") String userId) {
        init(session, tenantId, userId);
        // 加入set中
        webSocketSet.add(this);
        //发送初始数据
        this.sendInitNotice(tenantId);
    }

    /**
     * 连接关闭调用的方法
     */
    @Override
    @OnClose
    public void onClose() {
        LOGGER.info("通知关闭连接,用户id:{}", getUserId());
        // 从set中删除
        webSocketSet.remove(this);
    }

    /***
     * 初始消息推送
     */
    public void sendInitNotice(String tenantId){
        Page page=new Page(1,15);
        IPage<InvestigationTaskDetail> investigationTaskDetailIPage=investigationTaskDetailService.getInvestigationTaskDetailPage(page,tenantId);
        List<InvestigationTaskDetail> investigationTaskDetailList=investigationTaskDetailIPage.getRecords();
        if(investigationTaskDetailList == null || investigationTaskDetailList.size()<=0){
            return;
        }
        String jsonText=JSON.toJSONString(investigationTaskDetailList);
        this.sendMessage(jsonText);
    }

    /***
     * 消息推送
     * @param investigationTaskDetailList
     */
    public void sendNotice(List<InvestigationTaskDetail> investigationTaskDetailList) {
        Set<Long> ids=investigationTaskDetailList.stream().map(InvestigationTaskDetail::getId).collect(Collectors.toSet());
        investigationTaskDetailList = investigationTaskDetailService.getInvestigationTaskDetailById(ids);
        if(investigationTaskDetailList == null || investigationTaskDetailList.size()<=0){
            return;
        }
        String tenantId= investigationTaskDetailList.get(0).getTenantId();
        String jsonText=JSON.toJSONString(investigationTaskDetailList);
        for (Listener listener : webSocketSet) {
            if (listener.getTenantId() != null && listener.getTenantId().equals(tenantId)) {
                listener.sendMessage(jsonText);
            }
        }
    }

    //注入的时候后给类的service注入
    @Resource
    public  void setInvestigationTaskDetailService(InvestigationTaskDetailService investigationTaskDetailService) {
        InvestigationBigScreenListener.investigationTaskDetailService = investigationTaskDetailService;
    }
}
